//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package user_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/user_memo_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type BasicMemoInfoDbItem struct {
	Content string   `bson:"content"`
	TagList []string `bson:"tagList"`
	BgColor string   `bson:"bgColor"`
}

type MemoInfoDbItem struct {
	MemoId     string              `bson:"_id"`
	UserId     string              `bson:"userId"`
	BasicInfo  BasicMemoInfoDbItem `bson:"basicInfo"`
	CreateTime int64               `bson:"createTime"`
	UpdateTime int64               `bson:"updateTime"`
}

func (item *MemoInfoDbItem) ToMemoInfo() *user_memo_api.MemoInfo {
	return &user_memo_api.MemoInfo{
		MemoId: item.MemoId,
		BasicInfo: &user_memo_api.BasicMemoInfo{
			Content: item.BasicInfo.Content,
			TagList: item.BasicInfo.TagList,
			BgColor: item.BasicInfo.BgColor,
		},
		CreateTime: item.CreateTime,
		UpdateTime: item.UpdateTime,
	}
}

type _UserMemoDao struct {
	mc *mongo.Collection
}

func newUserMemoDao(db *mongo.Database) (*_UserMemoDao, error) {
	mc := db.Collection(db_ns.DB_NS_USER + "memo")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"userId", 1}, {"basicInfo.tagList", 1}, {"updateTime", 1}},
		},
		{
			Keys: bson.D{{"userId", 1}, {"updateTime", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_UserMemoDao{mc: mc}, nil
}

func (db *_UserMemoDao) Insert(ctx context.Context, dbItem *MemoInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_UserMemoDao) Exist(ctx context.Context, userId, memoId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": memoId, "userId": userId})
	return count > 0, err
}

func (db *_UserMemoDao) Get(ctx context.Context, userId, memoId string) (*MemoInfoDbItem, error) {
	retItem := &MemoInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": memoId, "userId": userId}).Decode(retItem)
	return retItem, err
}

func (db *_UserMemoDao) Remove(ctx context.Context, userId, memoId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": memoId, "userId": userId})
	return err
}

func (db *_UserMemoDao) Count(ctx context.Context, userId string, filterByTag bool, tagList []string) (uint32, error) {
	query := bson.M{"userId": userId}
	if filterByTag {
		query["basicInfo.tagList"] = bson.M{"$in": tagList}
	}
	count, err := db.mc.CountDocuments(ctx, query)
	return uint32(count), err
}

func (db *_UserMemoDao) List(ctx context.Context, userId string, filterByTag bool, tagList []string, offset, limit int64) ([]*MemoInfoDbItem, error) {
	query := bson.M{"userId": userId}
	if filterByTag {
		query["basicInfo.tagList"] = bson.M{"$in": tagList}
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"updateTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*MemoInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_UserMemoDao) Update(ctx context.Context, userId, memoId string, basicDbItem *BasicMemoInfoDbItem, updateTime int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": memoId, "userId": userId}, bson.M{
		"$set": bson.M{
			"basicInfo":  basicDbItem,
			"updateTime": updateTime,
		},
	})
	return err
}

func (db *_UserMemoDao) DistinctTag(ctx context.Context, userId string) ([]string, error) {
	itemList, err := db.mc.Distinct(ctx, "basicInfo.tagList", bson.M{"userId": userId})
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, item := range itemList {
		retList = append(retList, item.(string))
	}
	return retList, nil
}
